//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Xml;
using OpenLS.Core.Serialization;
using OpenLS.Drawing.Serialization;

namespace OpenLS.Drawing
{
    public class ThemeManager : IOfficeXmlSerializable
    {
        private List<Theme> themes = new List<Theme>();

        public List<Theme> Themes
        {
            get { return themes; }
            internal set { themes = value; }
        }

        #region IOfficeXmlSerializable Members

        void IOfficeXmlSerializable.ReadXml(ReadContext context)
        {
            using (context.Read("themeManager"))
            {
            }
            foreach (PackageRelationship relationship in context.Part.GetRelationships())
            {
                if (relationship.RelationshipType == DrawingConstants.ThemeRelationshipType)
                {
                    PackagePart themePart =
                        context.Part.Package.GetPart(
                            PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
                    Theme theme;
                    using (Stream stream = themePart.GetStream())
                    using (XmlTextReader xr = new XmlTextReader(stream))
                    {
                        ReadContext c = new ReadContext(xr, themePart, DrawingConstants.DrawingNamespaceUri);
                        theme = c.ReadElement<Theme>();
                    }
                    Themes.Add(theme);
                }
            }
        }

        void IOfficeXmlSerializable.WriteXml(WriteContext context)
        {
            using (var c = context.Write("themeManager"))
            {
                foreach (var theme in Themes)
                {
                    using (var relatedContext = c.CreateRelatedContext(DrawingConstants.DrawingNamespace,
                                                                       c.GetAvailableUri("themes/theme{0}.xml"),
                                                                       DrawingConstants.ThemeRelationshipType,
                                                                       DrawingConstants.ThemeContentType, false))
                    {
                        theme.WriteXml(relatedContext);
                    }
                }
            }
        }

        #endregion
    }
}